package com.commerce.weather.Activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowInsetsController;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.commerce.weather.Entity.DataWeather;
import com.commerce.weather.R;
import com.commerce.weather.Sevice.MyService;
import com.commerce.weather.adapter.MyListAdapter;
import com.commerce.weather.utils.CallLocation;
import com.commerce.weather.utils.DensityUtil;
import com.google.android.material.appbar.AppBarLayout;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements AppBarLayout.OnOffsetChangedListener, View.OnClickListener {
    private DataWeather dataWeather;

    private AppBarLayout appBar;
    private TextView bgContentwid;
    private TextView bgContentdp;
    private TextView bgContentdesc;
    private TextView contentToolbarOpen;
    private ImageView moreButton;
    private ImageView replaceButton;
    private ListView listView;
    private ProgressBar progressBar;
    private TextView qualityText;
    private TextView powerText;
    private TextView directionText;
    private String str="";
    private String city="";
    AMapLocationClient mLocationClient=null;
    Intent intent;
    SharedPreferences sp;
    SharedPreferences.Editor edit;
    private ImageView iv_Gif;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setWindows();
        setContentView(R.layout.activity_main);
        sp=getSharedPreferences("sign",MODE_PRIVATE);
        edit = sp.edit();
        permission();
        appBar = findViewById(R.id.app_bar);
        bgContentwid = findViewById(R.id.content_wid);
        bgContentdp = findViewById(R.id.content_dp);
        bgContentdesc = findViewById(R.id.content_desc);

        replaceButton = findViewById(R.id.tlex_replace);
        contentToolbarOpen = findViewById(R.id.tlex_title);
        moreButton = findViewById(R.id.tlex_more);

        listView = findViewById(R.id.mn_list_view);

        progressBar = findViewById(R.id.wx_progress);
        qualityText = findViewById(R.id.wx_quality);
        powerText = findViewById(R.id.wx_power);
        directionText = findViewById(R.id.wx_direction);

        iv_Gif = (ImageView) findViewById(R.id.img_gif);
        initView();
        //注册监听事件
        appBar.addOnOffsetChangedListener(this);
        setSupportActionBar((Toolbar) findViewById(R.id.tl_csn_toolbar));
        moreButton.setOnClickListener(this);
        replaceButton.setOnClickListener(this);
        setTypeface();

    }

    private void initView() {
        location();
    }

    /**
     * 字体设置
     */
    private void setTypeface(){
        Typeface tf = Typeface.createFromAsset(MainActivity.this.getAssets(), "fonts/mjnumber.otf");
        bgContentwid.setTypeface(tf);
        bgContentdp.setTypeface(tf);
        bgContentdesc.setTypeface(tf);
        contentToolbarOpen.setTypeface(tf);
        
    }
    /**
     * 设置透明状态栏导航栏
     */
    private void setWindows(){
        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R){
            WindowInsetsController windowInsetsController = getWindow().getDecorView().getWindowInsetsController();
            windowInsetsController.hide(WindowInsetsController.BEHAVIOR_SHOW_BARS_BY_SWIPE);
        }else if (Build.VERSION.SDK_INT >= 21){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }else {
            Window window = getWindow();
            window.setFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * 点击事件
     * @param view
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tlex_more:
                show();
                break;
            case R.id.tlex_replace:
                startActivityForResult(new Intent(this,ReActivity.class),1);
        }

    }
    /**
     * 主体滑动监听
     * @param appBarLayout 主体
     * @param verticalOffset   偏移量
     */
    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        //垂直方向偏移量
        int offset = Math.abs(verticalOffset);
        //最大偏移距离
        int scrollRange = appBarLayout.getTotalScrollRange();
        if (offset <= scrollRange / 2) {
            //当滑动没超过一半，展开状态下toolbar显示内容，根据收缩位置，改变透明值
            contentToolbarOpen.setText(city);
            //根据偏移百分比 计算透明值
            float scale2 = (float) offset / (scrollRange / 2);
            int alpha2 = (int) (255 * (1-scale2));
            //字体淡出
            contentToolbarOpen.setTextColor(Color.argb(alpha2, 255, 255, 255));
            bgContentwid.setTextColor(Color.argb(alpha2, 255, 255, 255));
            bgContentdp.setTextColor(Color.argb(alpha2, 255, 255, 255));
            bgContentdesc.setTextColor(Color.argb(alpha2, 255, 255, 255));

        } else {
            //当滑动超过一半，收缩状态下toolbar显示内容，根据收缩位置，改变透明值
            Log.d("TAG","offsety"+offset);
            contentToolbarOpen.setText(str);
            float scale3 = (float) (scrollRange  - offset) / (scrollRange / 2);
            int alpha3 = (int) (255 * (1-scale3));
            //字体淡入
            contentToolbarOpen.setTextColor(Color.argb(alpha3, 255, 255, 255));
        }
    }

    /**
     * 获取天气数据
     * @param location 地址
     */
    private void initData(String location){
        city=location;
        contentToolbarOpen.setText(location);
        edit.putString("city",city);
        edit.apply();
        Call call = new CallLocation().location(location, MainActivity.this);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showFailedDialog();
                    }
                });
            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                Log.d("TAG", "onResponse: "+string);
                Gson gson = new Gson();
                dataWeather = gson.fromJson(string, DataWeather.class);
                if(dataWeather!=null){
                final MyListAdapter myListAdapter = new MyListAdapter(MainActivity.this, dataWeather.getResult().getFuture());
                //无论是HttpURLConnection还是OkHttp最终的回调接口，即onResponse运行在子线程
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        DataWeather.ResultBean.RealtimeBean realtime = dataWeather.getResult().getRealtime();
                        bgContentwid.setText(realtime.getTemperature());
                        bgContentdesc.setText(realtime.getInfo());
                        int weather = type(realtime) ;
                        Glide.with(MainActivity.this).load(weather).into(iv_Gif);
                        str=realtime.getTemperature()+"℃/"+realtime.getInfo();
                        quality(realtime.getAqi());
                        powerText.setText(realtime.getDirect());
                        directionText.setText(realtime.getPower());
                        listView.setAdapter(myListAdapter);
                    }
                });
            }else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showFailedDialog();
                        }
                    });
                }
            }
        });

    }

    private int type(DataWeather.ResultBean.RealtimeBean item){
        int i = 0;
        if(item.getInfo().contains("雪")){
            i = R.drawable.yu;
        }else if (item.getInfo().contains("雷")){
            i = R.drawable.lei;
        }else if (item.getInfo().contains("雨")){
            i = R.drawable.yu;
        }else if (item.getInfo().contains("云")){
            i = R.drawable.yutian;
        }else{
            i = R.drawable.timg;
        }
        return i;
    }

    /**
     *
     * 高德定位
     */
    private void location(){
        //声明AMapLocationClientOption对象
        AMapLocationClientOption mLocationOption = null;
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。
        // 如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient = new AMapLocationClient(getApplicationContext()); ;
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        //可在其中解析amapLocation获取相应内容。
                        city = amapLocation.getCity().replace("市","");
                        Log.d("TAG", "onActivityfgResult: "+city);
                    }else {
                        city="北京";
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Log.e("AmapError","location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                        toOpenGPS(MainActivity.this);
                    }
                    initData(city);
                    mLocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
                    mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
                }
            }
        });
    }
    /**
     * 提示用户去开启定位服务
     **/
    public void toOpenGPS(Activity activity) {
        new AlertDialog.Builder(activity)
                .setTitle("提示")
                .setMessage("手机定位服务未开启，无法获取到您的准确位置信息，是否前往开启？")
                .setNegativeButton("取消",null)
                .setPositiveButton("去开启", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }
    /**
     * 空气进度条设置
     *
     * @param string
     */
    private void quality( String string){
        int i = Integer.parseInt(string);
        progressBar.setProgress(i);
        String s;
        if(i<50){
            s="优   "+i;
        }else if(i<100) {
            s="良   "+i;
        }else if(i<150) {
            s= "轻度 "+i;
        }else if(i<200) {
            s= "中度 "+i;
        }else if(i<300) {
            s= "重度 "+i;
        }else{
            s= "严重 "+i;
        }
        progressBar.setProgress(300-i);
        qualityText.setText(s);
    }



    /**
     * 弹出菜单栏
     */
    private void show() {
        Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_content_normal, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams)contentView.getLayoutParams();
        //设置布局
        params.leftMargin =DensityUtil.dip2px(this, 100f);
        params.topMargin = DensityUtil.dip2px(this, 50f);
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.TOP);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        final Switch check = contentView.findViewById(R.id.dcn_checkbox);
        Boolean sign = sp.getBoolean("sign", false);
        check.setChecked(sign);
        check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Boolean checked = check.isChecked();
                edit.putBoolean("sign",checked);
                edit.apply();
                intent = new Intent(MainActivity.this, MyService.class);
                if(checked){
                    startService(intent);
                }else {
                    stopService(intent);
                }
            }
        });
        bottomDialog.show();
        
    }
    /**
     * 到达上限时或者无网时对话框
     */
    private void showFailedDialog() {
        AlertDialog.Builder failedDialog = new AlertDialog.Builder(MainActivity.this);
        failedDialog.setIcon(R.drawable.logo);
        failedDialog.setTitle("加载失败");
        //设置对话框消息提示
        failedDialog.setMessage("\n         " + "抱歉数据获取异常");
        failedDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        failedDialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch(requestCode){
            case 1:
                if(resultCode==200){
                    Log.d("TAG", "onActivityResult: "+data.getStringExtra("district"));
                 initData(data.getStringExtra("district"));
                }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private  void permission(){
        if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{
                            Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    201);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode ==201){
            if (PackageManager.PERMISSION_GRANTED != grantResults[0]){
                //用户未授予权限定义中对应的权限
                //未授权，不能执行需要权限的操作。
                finish();
            }else{
                //已授权可以执行相应操作

            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    /**
     * 第一次返回退出应用提示
     */
    protected long exitTime; //记录第一次点击时的时间
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(MainActivity.this, "再按一次退出天气",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                MainActivity.this.finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        location();
        super.onResume();
    }
}